package org.bao.service;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.bao.bean.alertMessagesBean;
import org.bao.controller.ReceiveMsgController;
import org.bao.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
 * @author ：feller
 * @date ：Created in 2022/05/12 11:27
 * @description：发送钉钉消息
 * @version: 1.0
 */
@Service
public class PostDingtalkService {

    private final Logger logger = LoggerFactory.getLogger(ReceiveMsgController.class);

    DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=f227ff3361e1149556d92505d79169861b758aeb2423d2d03d85ca27b296d29f");
    OapiRobotSendRequest sendrequest = new OapiRobotSendRequest();

    public Response setMsg(alertMessagesBean alertMessagesBean) throws ApiException {
        logger.info("发送markdown格式");
        sendrequest.setMsgtype("markdown");
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(alertMessagesBean.getAlertRuleName());
        markdown.setText("#### "+alertMessagesBean.getAlertRuleName()+"\n" +
            "> "+alertMessagesBean.getMessage()+"\n\n" +
            "> "+alertMessagesBean.getAlertGroupType()+"\n\n" +
            "> "+alertMessagesBean.getAlertObject().toString()+"\n\n" +
            "> #### "+alertMessagesBean.getUrl()+" \n");

    sendrequest.setMarkdown(markdown);
    OapiRobotSendResponse response = client.execute(sendrequest);

    if (response.isSuccess()){
        logger.info("钉钉告警发送完成");
        return Response.success();
    }else{
        String getMsg = response.getMsg();
        long getErrcode = response.getErrcode();
        logger.info("钉钉告警发送失败 -> 钉钉错误码 -> {},错误日志 -> {}",getErrcode,getMsg);
        return Response.error(getMsg,(int)getErrcode);
    }
    }
}
